import React from 'react';
import {Form, Button , Breadcrumb ,Card , Steps , message} from 'antd';
import AppHelper from 'utils/AppHelper'
import HttpUtils from 'utils/HttpUtils'
import CreateStep1 from './create_step1'
import CreateStep2 from './create_step2'
import CreateStep3 from './create_step3'

const FormItem = Form.Item;
const steps = [{
    title: '基本信息',
}, {
    title: '规格信息',
}, {
    title: '属性信息',
}, {
    title: '完成',
}];

class ProductCreate extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            current: 1,
            getCurrentStyle : function (index) {
                if(this.current === index){
                    return {display:'block'};
                } else {
                    return {display:'none'}
                }
            },
            attributes : [],
            specs:[],
        };
        this.createUrl = AppHelper.config.serviceUrl + '/product';
    }

    next() {
        const current = this.state.current + 1;
        this.setState({current});
    }

    prev() {
        const current = this.state.current - 1;
        this.setState({current});
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (err) {
                console.log('Received values of form: ', values);
                return;
            }
            let data = {
                productGroup : {},
                attributes : [],
                products:[],
                tags:[]
            };
            data.productGroup = values.productGroup;
            data.productGroup.categoryId = values.productGroup.categoryId.slice(-1).join('');
            data.tags = values.productGroup.tags;
            
            let attributes = values.attributes;
            for(let attr in attributes){
                data.attributes.push({
                    'optionId' : attr,
                    'value' : attributes[attr]
                })
            }

            let products = values.products;
            for (var i = 0; i < products.length; i++) {
                let prod = products[i];
                let formatedSpecs = [];
                let specs = prod.specs;
                for(let id in specs){
                    formatedSpecs.push({
                        'optionId' : id,
                        'value' : specs[id]
                    })
                }
                prod.specList = formatedSpecs;

                let imgs = prod.imgs;
                let formatedImgs = [];
                for(let index in imgs){
                    formatedImgs.push({
                        'path' : imgs[index]
                    })
                }
                prod.imgList = formatedImgs;
            }

            data.products = products;

            message.loading('保存中',0);
            let self = this;
            HttpUtils.createProduct(data , {
                success(resp){
                    message.destroy();
                    self.props.history.push('/products')
                }
            })
        });
    }

    onCategoryChange = (catIds) =>{
        if (catIds.length == 3) {
            let catId = catIds.slice(-1);
            this.fetchSpecs(catId);
            this.fetchAttributes(catId);
        }
    }

    fetchSpecs = (catId) => {
        let self = this;
        HttpUtils.listSpecs({catId} , {
            success(resp){
                let specs = resp.data;
                self.setState({specs});
            }
        })
    }

    fetchAttributes = (catId) => {
        let self = this;
        HttpUtils.listAttributes({catId} , {
            success(resp){
                let attrOptions = resp.data;
                let attributes = [];
                for ( let i = 0; i < attrOptions.length; i++) {
                    let item = attrOptions[i];
                    let attr = {
                        id : item.id,
                        name : item.name,
                        inputType : item.inputType
                    };
                    let valueList = item.valueList;
                    if(valueList){
                        let options = [];
                        for (let j = 0; j < valueList.length; j++) {
                            let value = valueList[j];
                            options.push({
                                id : value.id,
                                value : value.value
                            })
                        }
                        attr.options = options;
                    }
                    attributes.push(attr);
                }
                self.setState({attributes});
            }
        })
    }

    render() {
        const {current} = this.state;
        return (
            <div>
                <Breadcrumb className="App-breadcrumb">
                    <Breadcrumb.Item>首页</Breadcrumb.Item>
                    <Breadcrumb.Item>商品管理</Breadcrumb.Item>
                    <Breadcrumb.Item>创建商品</Breadcrumb.Item>
                </Breadcrumb>
                <Card bordered={false}>
                    <Steps current={current-1} style={{ margin: '5px 0px 20px 0px'}}>
                        {steps.map(item => <Steps.Step key={item.title} title={item.title}/>)}
                    </Steps>
                    <Form onSubmit={this.handleSubmit}>
                        <div className="steps-content">
                            <CreateStep1 style={this.state.getCurrentStyle(1)} form={this.props.form} onCategoryChange={this.onCategoryChange}/>
                            <CreateStep2 style={this.state.getCurrentStyle(2)} form={this.props.form} specs={this.state.specs}/>
                            <CreateStep3 style={this.state.getCurrentStyle(3)} form={this.props.form} attributes={this.state.attributes}/>
                        </div>
                        <div className="steps-action">
                            {
                                this.state.current < steps.length - 1
                                &&
                                <Button type="primary" onClick={() => this.next()}>下一步</Button>
                            }
                            {
                                this.state.current === steps.length - 1
                                &&
                                <FormItem>
                                    <Button type="primary" htmlType="submit" size="large">保存</Button>
                                </FormItem>
                            }
                            {
                                this.state.current > 1
                                &&
                                <Button style={{marginLeft: 8}} onClick={() => this.prev()}>
                                    上一步
                                </Button>
                            }
                        </div>
                    </Form>
                </Card>
            </div>
        );
    }
}
const ProductCreatePage = Form.create()(ProductCreate);
export default ProductCreatePage;